import Vue from 'vue'
import Vuex from 'vuex'
import { Message } from 'element-ui'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    routerlist: [],
    userInfo: null,
    authorities: [],
    collapse: false, // 菜单收起展开开关
    isWebsocket: false,  // websocket是否连接
    overdueRemin: '' // 证书的过期提醒
  },
  getters: {
  },
  mutations: {
    // 添加用户信息
    SET_USERINFO(state, data) {
      state.userInfo = data
    },

    // 获取页面功能权限
    SET_AUTHOR(state, data) {
      state.authorities = data
    },

    // 菜单展开收起操作
    MENU_COLLAPSE(state, val) {
      state.collapse = val
    },

    // websocket
    handleWs(state, data) {
      state.overdueRemin += data.title + data.content
    },
    setWsStatus(state, flag) {
      state.isWebsocket = flag
    }
  },
  actions: {
    ws({ commit }, userId) {
      const wsUrl = {
        'development': 'ws://172.16.0.187:8081',
        'production': 'ws://172.17.0.5:8081',
        'test': 'ws://47.108.113.224:8081'
      }
      // 建立websocket链接
      const url = wsUrl[process.env.VUE_APP_RUNTIME_ENV]
      const websocket = new WebSocket(`${url}/webSocket/${userId}`)

      websocket.onopen = res => {
        console.log("已建立连接", res)
        commit('setWsStatus', true)
        // ws.send("Hello WebSockets!");
      }

      websocket.onmessage = res => {
        console.log('接收到消息', res)
        const data = JSON.parse(res.data)
        // 2: 踢下线,重新登录，3: 刷新token, 4: 证书过期提醒
        switch (data.type) {
          case 2:
            Message.error('权限变更，请重新登录')
            setTimeout(() => {
              window.localStorage.removeItem('token')
              window.open('/admin/login', '_self')
            }, 1000)
            break
          case 3:
            window.localStorage.setItem('token', data.msg)
            break
          case 4:
            console.log(data.msg)
            commit('handleWs', data.msg)
            break
        }
      }

      websocket.onclose = () => {
        console.info('WebSocket已关闭')
      }
    }
  },
  modules: {}
})

export default store